export interface Action {
    func: Function;
    context: any;
    args: any[];
}

export class FunctionStore {
    private _functionMap: Map<string, Action> = new Map<string, Action>();

    public add(
        name: string,
        func: Function,
        context: unknown = null,
        ...args: any[]
    ): void {
        this._functionMap.set(name, { func, context, args });
    }

    public get(name: string): Action | null {
        const act = this.get(name);
        if (act) {
            return act;
        }
        return null;
    }

    public call(name: string): any {
        const act = this.get(name);
        if (!act) {
            console.error(`Function ${name} not found`);
            return null;
        }
        return act.func.apply(act.context, act.args);
    }

    public remove(name: string): void {
        this._functionMap.delete(name);
    }

    public clear(): void {
        this._functionMap.clear();
    }
}

export function getCommand() {
    let self: any = globalThis;
    if (!self.command) {
        self.command = new FunctionStore();
        console.log('instance', self.command);
    }
    return self.command;
}

export const command = getCommand() as FunctionStore;
